package cc.jcizp.userservice.controller;

import cc.jcizp.userservice.domain.User;
import cc.jcizp.userservice.dto.ExecutionResult;
import cc.jcizp.userservice.enums.ExecutionStateEnum;
import cc.jcizp.userservice.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @RequestMapping(value = "/register")
    public ExecutionResult register(@Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return new ExecutionResult(ExecutionStateEnum.INFO_NOT_COMPLITE.getState(),
                    ExecutionStateEnum.INFO_NOT_COMPLITE.getInfo() + printErrorInfo(bindingResult), null);
        }
        return userService.registerUser(user);
    }

    @RequestMapping(value = "/authentication")
    public ExecutionResult authentication(@Valid User user, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return new ExecutionResult(ExecutionStateEnum.INFO_NOT_COMPLITE.getState(),
                    ExecutionStateEnum.INFO_NOT_COMPLITE.getInfo() + printErrorInfo(bindingResult),null);
        }
        return userService.authentication(user);
    }

    @RequestMapping(value = "/hello")
    public String hello(String name){
        return "hello " + name;
    }

    private String printErrorInfo(BindingResult bindingResult){
        StringBuffer errorInfo = new StringBuffer("[");
        for(ObjectError objectError : bindingResult.getAllErrors()){
            errorInfo.append(objectError.getDefaultMessage() + ",");
        }
        errorInfo.deleteCharAt(errorInfo.length()-1);
        errorInfo.append("]");
        return errorInfo.toString();
    }
}
